use std::io;
use std::io::Write;
use std::sync::atomic::Ordering::{ Relaxed, SeqCst};
use std::sync::atomic::{AtomicU8};
use std::thread::spawn;

static A: AtomicU8 = AtomicU8::new(0);
static B: AtomicU8 = AtomicU8::new(0);
static FLAG: AtomicU8 = AtomicU8::new(0);

fn main() {
    spawn(|| {
        loop {
            if FLAG.load(SeqCst) & 1 > 0 {
                B.store(1, Relaxed);
                 print!("{}", A.load(Relaxed));
                FLAG.fetch_xor(1, SeqCst);
            }
        }
    });
    spawn(|| {
        loop {
            if FLAG.load(SeqCst) & 2 > 0 {
                A.store(1,Relaxed);
                print!("{}", B.load(Relaxed));
                FLAG.fetch_xor(2, SeqCst);
            }
        }
    });

    loop {
        A.store(0, Relaxed);
        B.store(0, Relaxed);
        FLAG.fetch_xor(3, SeqCst);
        while FLAG.load(SeqCst) != 0 {}
        print!("\n");
        io::stdout().flush().unwrap();
    }
}

